package com.youchuang.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.StrutsStatics;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.opensymphony.xwork2.ActionContext;
import com.youchuang.bean.Book;
import com.youchuang.bean.Bulltion;
import com.youchuang.bean.Category;
import com.youchuang.bean.CategoryProduct;
import com.youchuang.bean.Comment;
import com.youchuang.bean.Indent;
import com.youchuang.bean.IndentItem;
import com.youchuang.bean.Manager;
import com.youchuang.bean.Product;
import com.youchuang.bean.User;
import com.youchuang.common.Constant;
import com.youchuang.dao.BookDAO;
import com.youchuang.dao.BulltionDAO;
import com.youchuang.dao.CategoryDAO;
import com.youchuang.dao.CategoryProductDAO;
import com.youchuang.dao.CommentDAO;
import com.youchuang.dao.IndentDAO;
import com.youchuang.dao.IndentItemDAO;
import com.youchuang.dao.ManagerDAO;
import com.youchuang.dao.ProductDAO;
import com.youchuang.dao.UserDAO;
import com.youchuang.service.AdminService;
import com.youchuang.util.CategoryProductUtil;
import com.youchuang.util.CategoryUtil;

@Transactional
@Service("adminService")
public class AdminServiceImpl implements AdminService {

	@Resource
	private ManagerDAO managerDAO;
	@Resource
	private CategoryProductDAO categoryProductDAO;
	@Resource
	private CategoryDAO categoryDAO;
	@Resource
	private ProductDAO productDAO;
	@Resource
	private BulltionDAO bulltionDAO;
	@Resource
	private CommentDAO commentDAO;
	@Resource
	private IndentDAO indentDAO;
	@Resource
	private UserDAO userDAO;
	@Resource
	private IndentItemDAO indentItemDAO;
	@Resource
	private BookDAO bookDAO;

	public AdminServiceImpl() {
	}

	@Override
	public List<Manager> findMangerByAll() {
		return managerDAO.queryAll();
	}

	@Override
	public List<CategoryProduct> findCategoryByProductIdSort(String id) {
		List<CategoryProduct> categoryProducts = categoryProductDAO.queryByProductId(id);
		CategoryProductUtil.sortByCatId(categoryProducts);
		return categoryProducts;
	}

	@Override
	public String findCategoryNameByCategoryId(String categoryId) {
		Category cnameCategory = categoryDAO.queryById(categoryId);
		String categoryName = null;
		if (cnameCategory != null) {
			categoryName = cnameCategory.getName();
		}
		return categoryName;
	}

	@Override
	public void updateProduct(Product product) {
		productDAO.update(product);
	}

	@Override
	public void saveBulltion(Bulltion bulltion) {
		bulltionDAO.save(bulltion);
	}

	@Override
	public int findCommentCountByAll() {
		return commentDAO.queryAllCount();
	}

	@Override
	public List<Comment> findCommentLimmit(int begin, int size) {
		return commentDAO.queryLimit(begin, size);
	}

	@Override
	public void deleteIndentById(String id) {
		Indent indent = indentDAO.queryById(id);
		indentDAO.delete(indent);

		List<IndentItem> list = indentItemDAO.queryByIndentId(id);
		for (IndentItem item : list) {
			indentItemDAO.delete(item);
		}
	}

	@Override
	public int findIndentCountByAll() {
		List<Indent> allIndent = indentDAO.queryAll();
		return allIndent.size();
	}

	@Override
	public List<Indent> findIndentLimmit(int begin, int size) {
		return indentDAO.queryLimit(begin, size);
	}

	@Override
	public void saveBook(Book book, String bigcate, String smallcate, File file, String fileFileName) {
		Product product = book.getProduct();
		productDAO.save(product);
		book.setId(product.getId());
		bookDAO.save(book);

		CategoryProduct categoryProduct1 = new CategoryProduct();
		categoryProduct1.setCategoryId(bigcate);
		categoryProduct1.setProductId(product.getId());

		CategoryProduct categoryProduct2 = new CategoryProduct();
		categoryProduct2.setCategoryId(smallcate);
		categoryProduct2.setProductId(product.getId());

		categoryProductDAO.save(categoryProduct1);
		categoryProductDAO.save(categoryProduct2);

		try {
			InputStream is = new FileInputStream(file);

			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
					.get(StrutsStatics.HTTP_REQUEST);
			String root = request.getSession().getServletContext().getRealPath("/productImages");
			File destFile = new File(root, fileFileName);
			OutputStream os = new FileOutputStream(destFile);

			byte[] buffer = new byte[400];
			int length = 0;
			while ((length = is.read(buffer)) > 0) {
				os.write(buffer, 0, length);
			}
			is.close();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Manager findManagerByAccount(String account) {
		return managerDAO.queryByAccount(account);
	}

	@Override
	public String updatePassword(String olderPassword, String password, String rePassword) {
		Map<String, Object> session = ActionContext.getContext().getSession();
		Manager admin = (Manager) session.get(Constant.A_USER);
		if (admin == null) {
			return Constant.ERROR;
		}
		if (password.trim().equals(rePassword.trim())) {
			if (admin.getPassword().trim().equals(olderPassword.trim())) {
				Manager saveAdmin = managerDAO.queryByAccount(admin.getAccount());
				saveAdmin.setPassword(password.trim());
				int i = managerDAO.update(saveAdmin);
				if (i != 0) {
					return Constant.SUCCESS;
				}
			} else {
				return Constant.ERROR;
			}
		}
		return Constant.ERROR;
	}

	@Override
	public void deleteProductById(String productId) {
		Product product = productDAO.queryById(productId);
		product.setHasDeleted(Constant.HAS_DELETE);
		productDAO.update(product);
	}

	@Override
	public int findProductCountByAll() {
		return productDAO.queryAllCount();
	}

	@Override
	public List<Product> findProductLimmitDescByAll(int begin, int size) {
		return productDAO.queryAllLimmitDesc(begin, size);
	}

	@Override
	public List<User> findUserByAll() {
		return userDAO.queryAll();
	}

	@Override
	public Product findProductById(String id) {
		return productDAO.queryById(id);

	}

	@Override
	public Category findCategoryById(String id) {
		return categoryDAO.queryById(id);
	}

	@Override
	public void updateCategory(Category category) {
		categoryDAO.update(category);
	}

	@Override
	public void saveOrUpdateCategory(Category category) {
		categoryDAO.saveOrUpdate(category);
	}

	@Override
	public void deleteCategoryByCategoryId(String categoryId) {
		Category cate = categoryDAO.queryById(categoryId);
		List<Category> list = categoryDAO.queryAll();
		List<Category> categories = CategoryUtil.getChilCategory(categoryId, list);
		categories.add(cate);
		for (Category category : categories) {
			categoryDAO.delete(category);
			categoryProductDAO.updateCategoryId(category.getId(), Constant.UNDEFINED);
		}
	}

}
